package com.larsgard.gedviewer.server.ged;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.larsgard.gedviewer.shared.entities.Person;

public class GedParserImplXml implements GedParser {

    private File file = new File("src/gedsource.xml");
    private final NodeList nodeLst;
    private int currentPosition = 0;

    public GedParserImplXml() throws XMLStreamException, ParserConfigurationException,
	    SAXException, IOException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document doc = db.parse(file);
	doc.getDocumentElement().normalize();
	System.out.println("Root element " + doc.getDocumentElement().getNodeName());
	nodeLst = doc.getElementsByTagName("FAMILY_TREE").item(0).getChildNodes();
	System.out.println("Found " + nodeLst.getLength() + " persons.");

	for (int i = 0; i < nodeLst.getLength(); i++) {

	    // Element currentElement = (Element) currentNode;
	    // String sex = currentElement.getAttribute("SEX");
	    // System.out.println(sex);
	    // NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("SEX");
	    // Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
	    // NodeList fstNm = fstNmElmnt.getChildNodes();
	    // System.out.println("First Name : " + (fstNm.item(0)).getNodeValue());
	    // NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
	    // Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
	    // NodeList lstNm = lstNmElmnt.getChildNodes();
	    // System.out.println("Last Name : " + (lstNm.item(0)).getNodeValue());

	}

    }

    @Override
    public Person read() throws XMLStreamException {
	Person result = null;
	while (true) {
	    NamedNodeMap attributes = nodeLst.item(currentPosition++).getAttributes();
	    if (attributes == null) {
		continue;
	    }
	    result = new Person();
	    result.setIdno(attributes.getNamedItem("idno").getNodeValue());

	    break;
	}
	return result;
    }

    @Override
    public Boolean hasNext() {
	return currentPosition <= nodeLst.getLength() - 2;
    }

    @Override
    public Person read(int pos) throws Exception {
	// TODO Auto-generated method stub
	return null;
    }

}
